package com.zhiyume.api.controller;

import com.zhiyume.api.util.ApiConstants;
import com.zhiyume.api.util.ApiOperateEnum;
import com.zhiyume.api.vo.DramaReq;
import com.zhiyume.dao.api.TDramaMapper;
import com.zhiyume.dao.api.TDramaPersonMapper;
import com.zhiyume.dao.api.TDramaSelfMapper;
import com.zhiyume.dao.entity.TDrama;
import com.zhiyume.dao.entity.TDramaCriteria;
import com.zhiyume.dao.entity.TDramaPerson;
import com.zhiyume.dao.entity.TDramaPersonCriteria;
import com.zhiyume.dao.entity.TDramaWithBLOBs;
import com.zhiyume.page.PageReq;
import com.zhiyume.page.Pager;
import com.zhiyume.service.IDramaService;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.JsonUtil;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * @description 剧相关请求接口
 */
@RestController
@RequestMapping("/api/drama")
@ApiIgnore
public class DramaAction {
    @Autowired
    private IDramaService iDramaService;

    @Autowired
    private TDramaMapper tDramaMapper;

    @Autowired
    private TDramaSelfMapper tDramaSelfMapper;

    @Autowired
    private TDramaPersonMapper tDramaPersonMapper;

    private String successType = ConstantEnum.CONSTANT_SUCCESS.getErrType();
    private String successMsg = ConstantEnum.CONSTANT_SUCCESS.getErrMsg();

    private static final Log log = LogFactory.getLog(DramaAction.class.getName());
    private static final String MODULE = DramaAction.class.getName();
    private static final List dramaTypes = Arrays.asList(TypeConstants.dramaTypeArr);
    /**
     * 根据id获取drama
     * @param id
     * @return
     */
    @GetMapping("/findDramaById")
    @ResponseBody
    public Map findDramaById(@RequestParam(defaultValue = "") String id){
        TDrama tDrama = null;
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(id))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else if(!StringUtil.isNumeric(String.valueOf(id))){
            result =JsonUtil.returnResult(ConstantEnum.CONSTANT_PARA_ERROR.getErrType(),ConstantEnum.CONSTANT_PARA_ERROR.getErrMsg());
        }else {
            tDrama = iDramaService.findDramaById(Long.parseLong(id));
            if(tDrama == null){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tDrama);
            }
        }
        return result;
    }

    /**
     * 根据剧名获取剧列表
     * @param name
     * @return
     */
    @GetMapping("/findDramaListByName")
    public Object findDramaListByName(@RequestParam(defaultValue = "") String name){
        List<TDrama> tDramaList = new ArrayList<>();
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(name))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else {
            tDramaList = iDramaService.findDramasListByName(name);
            if(tDramaList == null || tDramaList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tDramaList);
            }
        }
        return result;
    }

    /**
     * 根据导演获取剧列表
     * @param director
     * @return
     */
    @GetMapping("/findDramaListByDirector")
    public Object findDramaListByDirector(@RequestParam(defaultValue = "") String director){
        List<TDrama> tDramaList = new ArrayList<>();
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(director))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else {
            tDramaList = iDramaService.findDramasListByDirector(director);
            if(tDramaList == null || tDramaList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tDramaList);
            }
        }
        return result;
    }

    /**
     * 根据剧类别获取剧列表
     */
    @GetMapping("/findDramaListByType")
    public Object findDramaListByType(@RequestParam(defaultValue = "") String dramaType,
                                      @RequestParam(defaultValue = "0") int page,
                                      @RequestParam(defaultValue = "10") int pageSize){
        List<TDrama> tDramaList = new ArrayList<>();
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(dramaType))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else if(!StringUtil.isNumeric(dramaType)){
            result =JsonUtil.returnResult(ConstantEnum.CONSTANT_PARA_ERROR.getErrType(),ConstantEnum.CONSTANT_PARA_ERROR.getErrMsg());
        }else {
            tDramaList = iDramaService.findDramasListByType( page, pageSize, dramaType);
            if(tDramaList == null || tDramaList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tDramaList);
            }
        }
        return result;
    }


    /**
     * 根据出品公司获取剧列表
     */
    @GetMapping("/findDramaListByCompany")
    @ResponseBody
    public Map findDramaListByCompany(@RequestParam(defaultValue = "") String company){
        List<TDrama> tDramaList = new ArrayList<>();
        Map result = new HashedMap();
        if(StringUtil.isBlank(String.valueOf(company))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else {
            tDramaList = iDramaService.findDramaListByCompany(company);
            if(tDramaList == null || tDramaList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tDramaList);
            }
        }
        return result;
    }


    @RequestMapping("/list")
    @ResponseBody
    public Map queryDramas(DramaReq page){
        Pager p = null;
        try{
            if(page.getPageSize() > ApiConstants.MAX_NUM)
                throw new Exception("超过最大值");
            p = getDramaPager(page);
            return JsonUtil.returnResult(successType,successMsg,p);
        }catch (Exception e){
            log.error(MODULE,e);
            return JsonUtil.returnResult(ConstantEnum.CONSTANT_SYS_ERROR.getErrType(),ConstantEnum.CONSTANT_SYS_ERROR.getErrMsg());
        }
    }

    /**
     * @param page
     * @return
     */
    private Pager getDramaPager(DramaReq page){
        Pager p = new Pager();

        TDramaCriteria total = new TDramaCriteria();
        TDramaCriteria.Criteria total_c = total.createCriteria();

        TDramaCriteria total_title = new TDramaCriteria();
        TDramaCriteria.Criteria total_c_title = total_title.createCriteria();

        TDramaCriteria total_name = new TDramaCriteria();
        TDramaCriteria.Criteria total_c_name = total_name.createCriteria();

        TDramaCriteria total_theme = new TDramaCriteria();
        TDramaCriteria.Criteria total_c_theme = total_theme.createCriteria();

        TDramaCriteria total_director = new TDramaCriteria();
        TDramaCriteria.Criteria total_c_director = total_director.createCriteria();

        TDramaCriteria total_actor = new TDramaCriteria();
        TDramaCriteria.Criteria total_c_actor = total_actor.createCriteria();

        //审核通过
        total_c.andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
        //搜索关键词
        if(StringUtil.isNotBlank(page.getTitle())){
            total_c.andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
            total_c_title.andTitleLike("%"+page.getTitle()+"%")
                    .andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
            total_c_name.andNameLike("%"+page.getTitle()+"%")
                    .andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
            total_c_theme.andThemeLike("%"+page.getTitle()+"%")
                    .andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
            total_c_director.andDirectorLike("%"+page.getTitle()+"%")
                    .andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
            total_c_actor.andActorLike("%"+page.getTitle()+"%")
                    .andStatusEqualTo(TypeConstants.AppConstants.IF_DRAMA_SHOW);
        }

        total.or(total_c_title);
        total.or(total_c_name);
        total.or(total_c_director);
        total.or(total_c_theme);
        total.or(total_c_actor);

        orderAndSetId(page, total_c, total);

        p.setTotalCount(tDramaMapper.countByExample(total));
        //翻页
        total.setLimitStart(0);
        total.setLimitEnd(page.getPageSize());


        List<TDramaWithBLOBs> ts = new ArrayList<TDramaWithBLOBs>();

        ts = tDramaSelfMapper.selectByExampleWithBLOBs(total);
        List datas = loadData(ts);

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    private void orderAndSetId(PageReq page, TDramaCriteria.Criteria total_c, TDramaCriteria data) {
        if(ApiOperateEnum.UP.getName().equals(page.getHandle())){
            total_c.andIdGreaterThan(page.getDataId());
            data.setOrderByClause("id asc,`d_id` asc");
        }
        else if(ApiOperateEnum.DOWN.getName().equals(page.getHandle())){
            total_c.andIdLessThan(page.getDataId());
            data.setOrderByClause("id desc,`d_id` desc");
        }else if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            data.setOrderByClause("id desc,`d_id` desc");
        }else{
            data.setOrderByClause("id desc,`d_id` desc");
        }
    }

    private List loadData(List<TDramaWithBLOBs> dramas) {
        List list = new ArrayList();

        for(TDramaWithBLOBs drama:dramas){
            Map dataItem = new HashMap();
            Map temp = new HashMap();

            TDramaPersonCriteria pt = new TDramaPersonCriteria();
            TDramaPersonCriteria.Criteria pc = pt.createCriteria();
            pc.andDramaIdEqualTo(drama.getId()).andCIdEqualTo(1);
            List<TDramaPerson> pList = tDramaPersonMapper.selectByExample(pt);

            String imgUrl = drama.getDramaUrl();
            String[] imgUrls = imgUrl.split(TypeConstants.URL_SPLIT);
            temp.put("dataId",drama.getId());
            temp.put("imgUrl", Arrays.asList(imgUrls));
            temp.put("title",drama.getTitle());
            temp.put("name",drama.getName());
            temp.put("theme",dramaTypes.get(Integer.valueOf((StringUtil.isBlank(drama.getTheme())?"0":drama.getTheme()))));
            temp.put("actor",(pList.size()>0)?pList.get(0).getpName():"未知");
            temp.put("actorId",(pList.size()>0)?pList.get(0).getpId():-1);
            temp.put("actorUrl",(pList.size()>0)?pList.get(0).getpId():-1);


            TDramaPersonCriteria pt1 = new TDramaPersonCriteria();
            TDramaPersonCriteria.Criteria pc1 = pt1.createCriteria();
            pc1.andDramaIdEqualTo(drama.getId()).andCIdEqualTo(3);
            List<TDramaPerson> pList2 = tDramaPersonMapper.selectByExample(pt1);
            temp.put("director",(pList2.size()>0)?pList2.get(0).getpName():"未知");
            temp.put("directorId",(pList2.size()>0)?pList2.get(0).getpId():-1);
            temp.put("directorUrl",(pList2.size()>0)?pList2.get(0).getpId():-1);

            temp.put("dataId",drama.getId());
            temp.put("link",drama.getId());
            dataItem.put("item",temp);
            list.add(dataItem);
        }
        return list;
    }


}
